define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'other-page'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/order/index',
                    add_url: 'order/order/add',
                    edit_url: 'order/order/edit',
                    del_url: 'order/order/del',
                    multi_url: 'order/order/multi',
                    detail_url: 'order/order/detail',
                    status_url: 'order/order/status',//审核链接
                    table: 'order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                queryParams: function (params) {
                  //这里可以追加搜索条件
                  var filter = JSON.parse(params.filter);
                  var op = JSON.parse(params.op);
                  //这里可以动态赋值，比如从URL中获取admin_id的值，filter.admin_id=Fast.api.query('admin_id');
                  filter.sorter = 1;
                  op.sorter = "=";
                  params.filter = JSON.stringify(filter);
                  params.op = JSON.stringify(op);
                  return params;
                },
                columns: [
                    [
                        // {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'nb', title: __('订单编号')},
                        {field: 'dep_id', title: __('分公司'),visible: false,searchList:$.getJSON('auth/department/searchlist')},
                        {field: 'depid_text', title: __('分公司'),operate: false},
                        {field: 'deliverydate', title: __('交货时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('审核状态'),visible: false,searchList: [{id:'-1',name:'订单作废'},{id:'0',name:'订单待审核'},{id:'1',name:'订单审核通过'},{id:'2',name:'发货审核通过'},{id:'3',name:'订单完成'}]},
                        {field: 'deliverystatus', title: __('出库/发货'),visible: false,searchList: [{id:'-1',name:'订单作废'},{id:'0',name:'备货中\\代发货'},{id:'1',name:'已发货\\待审核\\发货已完成'},{id:'2',name:'已发货\\待审核\\发货未完成'},{id:'3',name:'确认收货\\已完成'}]},
                        {field: 'status_text', title: __('审核状态'), formatter: Controller.api.formatter.status,operate: false},
                        {field: 'deliverystatus_text', title: __('出库/发货'),formatter: Controller.api.formatter.deliverystatus,operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        //操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
                        {
                          field: 'operate',
                          width: "120px",
                          title: __('Operate'),
                          table: table,
                          events: Table.api.events.operate,
                          buttons: [
                            {
                              name: 'detail',
                              title: __('订单详情'),
                              text:'订单详情',
                              extend:"data-area='[\"70%\",\"70%\"]'",
                              classname: 'btn btn-xs btn-primary btn-dialog',
                              icon: 'fa fa-list',
                              url: 'order/order/detail',
                              callback: function (data) {
                                Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                              }
                            },
                            {
                              name: 'status',
                              icon: 'fa fa-sticky-note',
                              title: __('审核'),
                              text:'审核',
                              extend:" data-toggle=\"tooltip\" data-area='[\"70%\",\"70%\"]'",
                              url: 'order/order/detail',
                              classname: 'btn btn-xs btn-success btn-dialog',
                              hidden:function (row) {
                                if(row.status === 0)
                                {
                                  return false;
                                }
                                if(row.status === 2)
                                {
                                  return false;
                                }
                                return true;
                              }
                            },
                            {
                              name: 'status',
                              icon: 'fa fa-sticky-note',
                              title: __('出库'),
                              text:'出库',
                              extend:" data-toggle=\"tooltip\" data-area='[\"70%\",\"70%\"]'",
                              url: 'order/order/detail/ids/{ids}?dialog=1&second=1',
                              classname: 'btn btn-xs btn-success btn-dialog',
                              hidden:function (row) {
                                if(row.status == 1)
                                {
                                  return false;
                                }
                                return true;
                              }
                            }
                          ],
                          // formatter: Table.api.formatter.operate
                          formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        company: function () {
          // 初始化表格参数配置
          Table.api.init({
            extend: {
              index_url: 'order/order/company',
              add_url: 'order/order/add',
              edit_url: 'order/order/edit',
              del_url: 'order/order/del',
              multi_url: 'order/order/multi',
              detail_url: 'order/order/detail',
              status_url: 'order/order/status',//审核链接
              table: 'order',
            }
          });

          var table = $("#table");

          // 初始化表格
          table.bootstrapTable({
            url: $.fn.bootstrapTable.defaults.extend.index_url,
            pk: 'id',
            sortName: 'id',
            //设置默认搜索
            queryParams: function (params) {
              //这里可以追加搜索条件
              var filter = JSON.parse(params.filter);
              var op = JSON.parse(params.op);
              //这里可以动态赋值，比如从URL中获取admin_id的值，filter.admin_id=Fast.api.query('admin_id');
              filter.dep_id = dep_id;
              op.dep_id = "=";
              params.filter = JSON.stringify(filter);
              params.op = JSON.stringify(op);
              return params;
            },
            columns: [
              [
                // {checkbox: true},
                {field: 'id', title: __('Id')},
                {field: 'nb', title: __('订单编号')},
                {field: 'dep_id', title: __('分公司'),visible: false,searchList:$.getJSON('auth/department/searchlist')},
                {field: 'depid_text', title: __('分公司'),operate: false},
                {field: 'deliverydate', title: __('交货时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                {field: 'status', title: __('审核状态'),visible: false,searchList: [{id:'-1',name:'订单作废'},{id:'0',name:'订单待审核'},{id:'1',name:'订单审核通过'},{id:'2',name:'发货审核通过'},{id:'3',name:'订单完成'}]},
                {field: 'deliverystatus', title: __('出库/发货'),visible: false,searchList: [{id:'-1',name:'订单作废'},{id:'0',name:'备货中\\代发货'},{id:'1',name:'已发货\\待审核\\发货已完成'},{id:'2',name:'已发货\\待审核\\发货未完成'},{id:'3',name:'确认收货\\已完成'}]},
                {field: 'status_text', title: __('审核状态'), formatter: Controller.api.formatter.status,operate: false},
                {field: 'deliverystatus_text', title: __('出库/发货'),formatter: Controller.api.formatter.deliverystatus,operate: false},
                {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                //操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
                {
                  field: 'operate',
                  width: "120px",
                  title: __('Operate'),
                  table: table,
                  events: Table.api.events.operate,
                  buttons: [
                    {
                      name: 'detail',
                      title: __('订单详情'),
                      text:'订单详情',
                      extend:"data-area='[\"70%\",\"70%\"]'",
                      classname: 'btn btn-xs btn-primary btn-dialog',
                      icon: 'fa fa-list',
                      url: 'order/order/detail',
                      callback: function (data) {
                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                      }
                    },
                    {
                      name: 'status',
                      icon: 'fa fa-sticky-note',
                      title: __('审核'),
                      text:'审核',
                      extend:" data-toggle=\"tooltip\" data-area='[\"70%\",\"70%\"]'",
                      url: 'order/order/detail',
                      classname: 'btn btn-xs btn-success btn-dialog',
                      hidden:function (row) {
                        if(row.status === 0)
                        {
                          return false;
                        }
                        if(row.status === 2)
                        {
                          return false;
                        }
                        return true;
                      }
                    },
                    {
                      name: 'status',
                      icon: 'fa fa-sticky-note',
                      title: __('出库'),
                      text:'出库',
                      extend:" data-toggle=\"tooltip\" data-area='[\"70%\",\"70%\"]'",
                      url: 'order/order/detail/ids/{ids}?dialog=1&second=1',
                      classname: 'btn btn-xs btn-success btn-dialog',
                      hidden:function (row) {
                        if(row.status == 1)
                        {
                          return false;
                        }
                        return true;
                      }
                    }
                  ],
                  // formatter: Table.api.formatter.operate
                  formatter: Table.api.formatter.buttons
                },
              ]
            ]
          });

          // 为表格绑定事件
          Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
          $(document).on("click", ".btn-addone", function () {
            var Obj = $(this);
            var parentObj = $('#goods_list-tab');
            var DomLen = parentObj.find('tr').length;
            var ids= new Array();
            var goods_ids = $('#goods_ids').val();
            ids =  goods_ids.split(',');
            var   Html = '';
            Html += '<tr>';
            Html += '<td>'+DomLen+'</td>';
            Html += '<td>';
            Html += '<a href="javascript:;" class="btn btn-xs btn-success btn-addone" title=""><i class="fa fa-plus"></i></a>';
            Html += '<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title=""><i class="fa fa-minus"></i></a>';
            Html += '</td>';
            Html += '<td width="30%" style="position: relative;">';
            Html += '<a href="javascript:;" class="btn btn-xs btn-success btn-more fagoods" title=""><i class="fa fa-ellipsis-h"></i></a>';
            Html += '<div class="input-goods_name">输入商品名称</div>';
            Html +='<input id="c-goods_name" class="form-control selectdom goods_name" style="display: none;"  name="row[enter_number][]" type="text" value="" placeholder="商品名称" >';
            Html +='<div class="col-xs-12 serchGoodsBox row sp_result_area shadowUp">';
            Html +='<ul class="sp_results goods_list pageDiv">';
            Html +='</ul>';
            Html +='<div class="page">';
            Html +='<ul class="pageMenu clearfix">';
            Html +='<li class="firstPage">首页</li>';
            Html +='<li class="prevPage"> < </li>';
            Html +='<div class="pageObj clearfix">';
            Html +='</div>';
            Html +='<li class="nextPage"> > </li>';
            Html +='<li class="lastPage">尾页</li>';
            Html +='<li class="last" style="display: none;">';
            Html +='共<span class="totalPage"></span>页，跳转至 <input type="number" class="keuInput" value="1">';
            Html +='<button type="button" class="btnSure">确定</button>';
            Html +='</li>';
            Html +='</ul>';
            Html +='</div>';
            Html +='</div>';
            Html +='</td>';
            Html += '<td><input id="c-num" class="form-control" name="row[goods][goods_num][]" type="number" type="number" value="1" min="1"></td>';
            Html += '<td><input id="c-remark" class="form-control" name="row[goods][remark][]" type="text" value="" placeholder="请输入备注信息，最多不超过200字" ></td>';
            Html += '</tr>';
            parentObj.append($(Html));
            if(Obj.parents('#goods_list-tab').find('tr').length > 2){
              Controller.api.addDelHtml(Obj);
            }

          });

          //删除一个
          $(document).on("click", ".btn-delone", function () {
            var ids= new Array();
            var goods_ids = $('#goods_ids').val();
            ids = goods_ids ?  goods_ids.split(',') : goods_ids ;
            var parentObj = $('#goods_list-tab');
            var ObjID = $(this).parents('tr').data('id');
            var indexno = ObjID ? $.inArray(ObjID.toString(),ids) : '';
            if(parentObj.find('tr').length > 2){
              if(indexno !== ''){
                ids.splice(indexno,1);
                $('#goods_ids').val(ids.join(','));
                //调用
                Controller.api.selcetCallback();
              }

              $(this).parents('tr').remove();

              //排序
              Controller.api.sortCallback();
            }

            if(parentObj.find('tr').length < 3){
              parentObj.find('tr').eq(1).find('td').eq(1).find('.btn-delone').remove();
            }

          });

          //或得焦点
          $(document).on("click", ".input-goods_name", function (event) {
            $('.serchGoodsBox').hide();
            event.stopPropagation();//阻止事件冒泡
            var ids= new Array();
            var goods_ids = $('#goods_ids').val();
            ids = goods_ids ?  goods_ids.split(',') : goods_ids ;
            $(this).hide();
            $(this).nextAll('.goods_name').show().focus();

            $('.goods_list').find('li').each(function(e){
              var Othis = $(this);
              var dataId = String(Othis.data('id'));
              if($.inArray(dataId, ids) != '-1'){
                Othis.addClass('disabled');
              }
            });
            Controller.api.ajaxFun($(this).nextAll('.goods_name'));

          });

          $(document).on("click", ".pageMenu", function (event) {
            event.stopPropagation();//阻止事件冒泡
          });

          //点击空白处，下拉框隐藏-------开始
          $(document).bind("click",function(e){//点击空白处，设置的弹框消失
            e.stopPropagation();//阻止事件冒泡
            //if(pop == class){return false;}
            $('.serchGoodsBox').hide();
            $('.goods_name').hide();
            $('.input-goods_name').show();
          });
          //点击空白处，下拉框隐藏-------结束


          //点击商品
          $(document).on("click", ".goodsdom", function () {
            var ids= new Array();
            var goods_ids = $('#goods_ids').val();
            ids = goods_ids ?  goods_ids.split(',') : goods_ids ;
            var valStr = '';
            var Othis = $(this);

            if(Othis.hasClass('disabled')) return false;

            var dataId = String(Othis.data('id'));

            if($.inArray(dataId, ids) == '-1' && ids){
              ids.push(Othis.data('id'));
            }
            Othis.parents('tr').attr('data-id', Othis.data('id'));
            valStr = ids ? ids.join(',')  : Othis.data('id');
            $('#goods_ids').val(valStr);
            Othis.parents('td').html(Othis.text() + '<input id="goods_id"  name="row[goods][goods_id][]" type="hidden" value="'+Othis.data('id')+'" >');
          });

          $(document).on("keyup", ".goods_name", function () {
            Controller.api.ajaxFun($(this));
          });

          $(document).on("blur", ".goods_name", function () {
            // $(this).val('');
          });

          $(document).on("click", ".fagoods", function () {
            Controller.api.goodsSelect($(this));
            $('.serchGoodsBox').hide();
            $('.goods_name').hide();
            $('.input-goods_name').show();
          });

          //定时控制重复提交
          $(document).on("click", "[type=submit]", function () {
            var Othis = $(this);
            $(this).attr('disabled', true);
            setTimeout(function(){
              Othis.attr('disabled', false);
            }, 3000);
            $("#add-form").submit();
          });


          //或得焦点
          $(document).on("blur", "#c-num", function () {
            if($(this).val() == '' || $(this).val() < 1 ){
              $(this).val(1);
            }
          });
          //修改地址
          $(document).on('click','.address-edit',function () {
            Fast.api.open('/index/goods/addressEdit/ids/'+$(this).attr('data-orderId'))
          });
        },
        edit: function () {
            Controller.api.bindevent();
        },
        status: function () {
          Controller.api.bindevent();
        },
        detail: function () {
          Controller.api.bindevent();
          //发货
          $(document).on('click','.btn-fahuo',function () {
            Fast.api.open('order/order/edit/ids/'+$(this).attr('data-id'));
          });
          //删除订单详情
          $(document).on('click ','.btn-delone',function (e) {
            e.stopPropagation();
            e.preventDefault();
            var that = this;
            var top = $(that).offset().top - $(window).scrollTop();
            var left = $(that).offset().left - $(window).scrollLeft() - 260;
            if (top + 154 > $(window).height()) {
              top = top - 154;
            }
            if ($(window).width() < 480) {
              top = left = undefined;
            }
            Layer.confirm(
              __('Are you sure you want to delete this item?'),
              {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
              function (index) {
                var id = $(that).attr('data-id');
                Fast.api.ajax({
                  url:'order/order/delItem/ids/'+id
                },function () {
                  //移除数据
                  $(that).parent().parent().remove();
                });
                Layer.close(index);
              }
            );
          });
          //修改订单详情数量
          $(document).on('change','.edit-numerb',function () {
            var id = $(this).attr('data-id');
            var number = $(this).val();
            Fast.api.ajax({
              url:'order/order/editNum/ids/'+id,
              data:{number:number}
            });
          });
          //作废订单  通过订单
          $(document).on('click', '.btn-more', function () {
            var that = this;
            var title = $(that).attr('data-title');
            var status = $(that).attr('data-status');
            Layer.confirm(
              title, {icon: status, title: __('Warning'),  shadeClose: true},
              function (index) {
                var id = $(that).attr('data-id');
                Fast.api.ajax({
                  url:'order/order/status/ids/'+id,
                  data:{status:status}
                },function () {
                  parent.$(".btn-refresh").trigger("click");//刷新父级元素
                  window.location.reload();

                });
                Layer.close(index);
              }
            );
          });
          //修改订单备注
          $(document).on('change','.remark',function () {
            Fast.api.ajax({
                url:'order/order/remark/ids/'+$('.address-edit').attr('data-orderId'),
                data:{remark:$(this).val()}
              }, function(data, ret){
                //成功的回调
                layer.msg(ret.msg);
                return false;
              }, function(data, ret){
                //失败的回调
                layer.msg(ret.msg);
                return false;
              });
          });
          //修改地址
          $(document).on('click','.address-edit',function () {
            Fast.api.open('/index/goods/addressEdit/ids/'+$(this).attr('data-orderId'))
          });
          //修改库存发货数量
          $('.edit-nums').blur(function () {
            if(parseInt($(this).val()) > $(this).attr('data-num'))
            {
              $(this).val($(this).attr('data-num'));
              layer.msg('出库数量不能大于订购数量');
              return false;
            }
          });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            selcetCallback: function(){
              var ids= new Array();
              var goods_ids = $('#goods_ids').val();
              ids = goods_ids ?  goods_ids.split(',') : goods_ids ;
              $('.goods_list').find('li').each(function(e){
                var Othis = $(this);
                var dataId = String(Othis.data('id'));
                if($.inArray(dataId, ids) != '-1'){
                  Othis.addClass('disabled');
                }else{
                  Othis.removeClass('disabled');
                }
              });
            },
          //重新排序
          sortCallback: function(){
            $('#goods_list-tab').find('tr').each(function(e){
              $(this).find('td').eq(0).text(e);
            });
          },
          ajaxFun: function(obj){
            var ids= new Array();
            var goods_ids = $('#goods_ids').val();
            ids = goods_ids ?  goods_ids.split(',') : goods_ids ;
            var goods_name = obj.val() ? obj.val() : '0';
            obj.parents('tr').find(".serchGoodsBox").pageFun({  /*在本地服务器上才能访问哦*/
              interFace:"ajax/getgoods/goods_name/"+goods_name,  /*接口*/
              displayCount:10,  /*每页显示总条数*/
              maxPage:5,/*每次最多加载多少页*/
              dataFun:function(data){
                var dataId = String(data.id);
                if($.inArray(dataId, ids) != '-1'){
                  var dataHtml = '<li data-id="'+data.id+'" class="goodsdom disabled">'+data.cname+'</li>';
                }else{
                  var dataHtml = '<li data-id="'+data.id+'" class="goodsdom">'+data.cname+'</li>';
                }
                return dataHtml;
              },
              pageFun:function(i){
                var pageHtml = '<li class="pageNum">'+i+'</li>';
                return pageHtml;
              }
            });

            Controller.api.selcetCallback();
            obj.parents('tr').find('.serchGoodsBox').show();
          },
          goodsSelect: function (obj) {
            var that = obj;
            var goods_ids =  $('#goods_ids').val() ? $('#goods_ids').val()  : 0;
            parent.Fast.api.open("store/preproduct/select?goods_ids=" + goods_ids + "&multiple=true&goods_ids="+ goods_ids  , __('Choose'), {
              callback: function (data) {
                var ids= new Array();
                var goods_ids = $('#goods_ids').val();

                if(data.multiple){//多选
                  var Html ='';
                  ids = goods_ids ?  goods_ids.split(',') : Array() ;
                  $.each(data.list, function (i, j) {
                    ids.push(j.id);
                    Controller.api.createHtml(that, j);
                  });

                  valStr = ids ? ids.join(',')  : data.ids;
                  $('#goods_ids').val(valStr);

                }else{//单选
                  ids = goods_ids ?  goods_ids.split(',') : goods_ids ;

                  if(goods_ids.indexOf(data.ids) == '-1' && ids){
                    ids.push(data.ids);
                  }

                  that.parents('tr').attr('data-id', data.ids);
                  valStr = ids ? ids.join(',')  : data.ids;
                  $('#goods_ids').val(valStr);

                  that.parents('td').html(data.goods_name + '<input id="goods_id"  name="row[goods][goods_id][]" type="hidden" value="'+data.ids+'" >');
                }
                Controller.api.addDelHtml(that);

              }
            });

          },
          //弹出层选择商品
          createHtml: function(obj, data){
            var parentObj = $('#goods_list-tab');
            var DomLen = parentObj.find('tr').length;
            var   Html = '';
            Html += '<tr data-id="'+data.id+'">';
            Html += '<td>'+DomLen+'</td>';
            Html += '<td>';
            Html += '<a href="javascript:;" class="btn btn-xs btn-success btn-addone" title=""><i class="fa fa-plus"></i></a>';
            Html += '<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title=""><i class="fa fa-minus"></i></a>';
            Html += '</td>';
            Html += '<td width="30%" style="position: relative;">';
            Html += '<input id="goods_id"  name="row[goods][goods_id][]" type="hidden" value="'+data.id+'">';
            Html += data.cname;
            Html +='</td>';
            Html += '<td><input id="c-num" data-storenum="'+data.storenum+'"  class="form-control" name="row[goods][goods_num][]" type="number" value="1" min="1"></td>';
            Html += '<td><input id="c-remark"  class="form-control" name="row[goods][remark][]" type="text" value="" placeholder="请输入备注信息，最多不超过200字"></td>';
            Html += '</tr>';
            parentObj.append($(Html));
          },
          //追加删除按钮
          addDelHtml: function(obj){
            var AppendDom = obj.parents('#goods_list-tab').find('tr').eq(1).find('td').eq(1);
            var delOne = AppendDom.find('.btn-delone');
            if(delOne.attr('class') == undefined){
              AppendDom.append('<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title=""><i class="fa fa-minus"></i></a>');
            }
          },
          //数据分页
          pageFun: function(){

          },
          formatter: {//渲染的方法
            status: function (value, row, index) {
              var color = 'success';
              if(row.status < 0)
              {
                color = 'danger';
              }
              if(row.status == 0)
              {
                color = 'yellow';
              }
              return '<span class="text-'+color+'"><i class="fa fa-circle"></i>'+row.status_text+'</span>';
            },
            deliverystatus: function (value, row, index) {
              var color = 'success';
              if(row.deliverystatus < 0)
              {
                color = 'danger';
              }
              if(row.deliverystatus == 0)
              {
                color = 'yellow';
              }
              return '<span class="text-'+color+'"><i class="fa fa-circle"></i>'+row.deliverystatus_text+'</span>';
            }
          }
        }
    };
    return Controller;
});